var request = require('../../../utils/request.js');
var config = require('../../../config.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    datalist: [],
    from: '',
  },


  onShow: function () {
    this.getAddressLst();
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      from: options.from
    });
  },


  onAddTap: function (event) {
    let url = '/pages/address/edit/address?type=add';
    wx.navigateTo({
      url: url,
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },


  onItemTap: function (event) {
    var address = event.currentTarget.dataset.itemdata;
    if (this.data.from == 'settle') {
      // 选中返回
      var pages = getCurrentPages();
      var superpage = pages[pages.length - 2];
      console.log(address);
      superpage.setData({
        address_id: address.id,
        address: address
      })
      wx.navigateBack({})
    } else {
      wx.navigateTo({
        url: '../edit/address?type=edit&address=' + JSON.stringify(address),
      });
    }
  },


  onItemLongTap: function (event) {
    var address = event.currentTarget.dataset.itemdata;
    console.log(address);
    var self = this;
    wx.showActionSheet({
      itemList: ['编辑', '删除'],
      success: function (event) {
        console.log(event.tapIndex)
        if (event.tapIndex == 0) {
          wx.navigateTo({
            url: '../edit/address?type=edit&address=' + JSON.stringify(address),
          });
        } else if (event.tapIndex == 1) {
          self.delAddressAction(address.id);
        }
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  },
  

delAddressAction:function(id){
  var url = config.delAddressUrl;
  var params = {
    id: id
  };
  var self = this;
  request.requestPost(url , params)
  .then(data => {
    self.getAddressLst();
  }).catch(msg => {
    console.log(msg);
  });
},

  /**
   * 获取地址列表
   */
  getAddressLst: function () {
    var url = config.addressLstUrl;
    var params = {};
    request.requestPost(url, params)
      .then(data => {
        this.setData({
          datalist: data
        })
      }).catch(msg => {
        console.log(msg);
      });
  }
})